﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Volo.Abp.Linq;
using YaAppoint.Common;
using YaAppoint.Response;
using YaAppoint.TextTemplates;

namespace YaAppoint.PrintTemplates
{
    [RemoteService(isEnabled: false)]
    public class PrintTemplateAppService(IRepository<PrintTemplate,Guid> templateRepository,
                                         IMapper mapper,
                                         IGuidGenerator guidGenerator,
                                         ICommonAppService commonAppService,
                                         IRepository<TextTemplate,Guid> textTemplateRepository,
                                         AsyncQueryableExecuter queryableExecuter) : ApplicationService, IPrintTemplateAppService, ITransientDependency
    {
        private readonly IRepository<PrintTemplate, Guid> _templateRepository = templateRepository;
        private readonly IMapper _mapper = mapper;
        private readonly AsyncQueryableExecuter _queryableExecuter = queryableExecuter;
        private readonly ICommonAppService _commonService = commonAppService;
        private readonly IGuidGenerator _guidGenerator = guidGenerator;
        private readonly IRepository<TextTemplate, Guid> _textTemplateRepository = textTemplateRepository; 




        public BackJson GetPrintTypeOptions()
        {

            var values = Enum.GetValues(typeof(PrintType));
            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            foreach (Enum item in values)
            {
                data.Add(new Dictionary<string, object> {
                    { "value",Convert.ToInt32(item)},
                    { "label",_commonService.GetEnumValueDescription(item)}
                });
            }
            return new BackJson
            {
                code = 0,
                data = data
            };
        }


        /// <summary>
        /// 提交创建
        /// </summary>
        public async Task<BackJson> CreateSubmit(CreatePrintTemplateDto dto)
        {
            var template = _mapper.Map<CreatePrintTemplateDto, PrintTemplate>(dto);
            await _templateRepository.InsertAsync(template);

            return new BackJson
            {
                code = 0,
                msg = "创建成功"
            };
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        public async Task<BackJson> DeleteTemplate(Guid id)
        {
            var template = await _templateRepository.FirstOrDefaultAsync(t => t.Id == id);
            if (template != null)
            { 
                await _templateRepository.DeleteAsync(template);
            }

            return new BackJson
            {
                code = 0,
                msg = "已删除"
            };
        }

        /// <summary>
        /// 提交编辑
        /// </summary>
        public async Task<BackJson> EditSubmit(PrintTemplateDto dto)
        {
            var template = await _templateRepository.FirstOrDefaultAsync(t => t.Id == dto.Id);

            if (template != null)
            {
                _mapper.Map<PrintTemplateDto, PrintTemplate>(dto, template);
                await _templateRepository.UpdateAsync(template);
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.PrintTemplateNotExist);
            }
           
            return new BackJson()
            {
                code=0,
                msg="保存成功"
            };
        }

        /// <summary>
        /// 加载详情
        /// </summary>
        public async Task<BackJson> LoadDetail(Guid id)
        {
            var template = await _templateRepository.FirstOrDefaultAsync(t => t.Id == id);
            if (template == null)
            {
                throw new BusinessException(CustomErrorCodes.PrintTemplateNotExist);
            }

            return new BackJson
            {
                code = 0,
                data = _mapper.Map<PrintTemplate, PrintTemplateDto>(template)
            };
        }


        /// <summary>
        /// 加载模板列表
        /// </summary>
        public async Task<BackJson> LoadTemplateList(Guid depId, Guid deviceTypeId,string filterName,PrintType? printType)
        {
            var query = await _templateRepository.GetQueryableAsync();
            if (!string.IsNullOrEmpty(filterName))
            {
                query = query.Where(t => t.Name.Contains(filterName));
            }

            if (printType != null)   
            {
                query = query.Where(t => t.PrintType.Equals(printType));
            }
            query = query.Where(t => t.DepartmentId==depId && t.DeviceTypeId==deviceTypeId);
            query = query.OrderBy(t => t.PrintType).ThenBy(t => t.Order);
            var list = await _queryableExecuter.ToListAsync(query);
            var data = _mapper.Map<List<PrintTemplate>, List<PrintTemplateDto>>(list);
            return new BackJson
            {
                code = 0,
                data = data.Select(item => new { 
                    id=item.Id,
                    name=item.Name,
                    printType=item.PrintType,
                    department=item.Department,
                    departmentId=item.DepartmentId,
                    deviceType= item.DeviceType,
                    deviceTypeId =item.DeviceTypeId,
                    isActive = item.IsActive,
                    order = item.Order,
                    key = _guidGenerator.Create().ToString()
                })
            };
        }

        /// <summary>
        /// 保存模板内容JSON
        /// </summary>
        public async Task<BackJson> SaveSchema(SaveSchemaDto dto)
        {
            var template = await _templateRepository.FirstOrDefaultAsync(t => t.Id == dto.Id);
            if (template == null)
            {
                throw new BusinessException(CustomErrorCodes.PrintTemplateNotExist);
            }
            template.JsonContent =dto.Schema;
            await _templateRepository.UpdateAsync(template);
            return new BackJson()
            {
                code = 0,
                msg = "保存成功"
            };
        }

        /// <summary>
        /// 获取模板绑定字段集合
        /// </summary>
        /// <param name="tempaltId"></param>
        /// <returns></returns>
        public async Task<BackJson> GetTemplateFields(Guid templateId)
        {
            var res = new BackJson();
            var printTempalte = await _templateRepository.FirstOrDefaultAsync();
            if (printTempalte == null)
            {
                res.code = 1;
                res.err = "打印模板不存在";
            }
            else
            {
                // 预约小票
                if (printTempalte.PrintType == PrintType.Appointment)
                {
                    var textTemplate = await _textTemplateRepository.FirstOrDefaultAsync(t=>t.Name.Contains("预约小票打印字段JSON")&&
                                                                                            t.Type== TemplateType.Json);
                    if (textTemplate == null)
                    {
                        res.code = 1;
                        res.err = "预约小票字段JSON模板不存在";
                    }
                    else
                    {
                        res.code = 0;
                        res.data = textTemplate.Content;
                    }
                }
                else
                {
                    var textTemplate = await _textTemplateRepository.FirstOrDefaultAsync(t => t.Name.Contains("签到小票打印字段Json")
                                                                                             && t.Type == TemplateType.Json);
                    if (textTemplate == null)
                    {
                        res.code = 1;
                        res.data = "签到小票字段JSON模板不存在";
                    }
                    else
                    {
                        res.code = 0;
                        res.data = textTemplate.Content;
                    }
                }
            }
            return res;
        }
    }
}
